﻿using System;
using System.ComponentModel;
using System.Web.Security;
using System.Web.UI.WebControls;
using BusinessLogic;
using BusinessLogic.Model;
using BusinessLogic.StateManagers;
using Mvp.NewsItems;
using BusinessLogic.Model.Repository;

namespace WebControls
{
    public partial class NewsItemControl : BaseControl, INewsItemControlView
    {

        #region Properties

        public NewsItem NewsItem { get; set; }

        [DefaultValue(true)]
        public bool ShowCommentsLink { get; set; }

        [DefaultValue(false)]
        public bool ShowFullText { get; set; }

        #endregion

        #region PageEvents

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (Roles.IsUserInRole(Constants.Roles.Admin))
            {
                pnlAdministration.Visible = true;
            }

            lbPostAuthor.Text = NewsItem.AuthorUsername;
            lbPostDate.Text = NewsItem.PostDate.ToTimeAdjustedString();

            hlEdit.NavigateUrl = "~/Admin/EditNewsItem.aspx?" + QueryStringConstants.NewsItemID + "=" + NewsItem.NewsItemID;

            string viewNewsItemUrl = "~/ViewNewsItem.aspx?" + QueryStringConstants.NewsItemID + "=" + NewsItem.NewsItemID;
            hlPostTitle.NavigateUrl = viewNewsItemUrl;
            hlPostTitle.Text = NewsItem.Title;
            
            if (ShowFullText)
            {
                ltPostText.Text = String.IsNullOrEmpty(NewsItem.Text) ? NewsItem.ShortText : NewsItem.Text;
            }
            else
            {
                ltPostText.Text = NewsItem.ShortText;
            }

            //add tags
            foreach (Tag t in NewsItem.Tags)
            {
                phTags.Controls.Add(new HyperLink { Text = t.TagValue, NavigateUrl = "~/Main.aspx?" + QueryStringConstants.Tag + "=" + t.TagValue });
                phTags.Controls.Add(new Literal { Text = "&nbsp;" });
            }

            if (ShowCommentsLink)
            {
                hlComments.Visible = true;
                //check if news has full text
                //add comments number
                hlComments.NavigateUrl = viewNewsItemUrl;
                hlComments.Text = "View "
                    + (!String.IsNullOrEmpty(NewsItem.Text) ? "full text and " : "") //add text to indicate news item has full text
                    + "comments(" + NewsItem.CommentsCount + ")";
            }
            else
            {
                hlComments.Visible = false;
            }

            //check if news has been edited
            if (NewsItem.LastEditedDate != null)
            {
                //add last editor and last edited date
                lastEdit.Visible = true;
                lbLastEditDate.Text = NewsItem.LastEditedDate.Value.ToTimeAdjustedString();
                lbLastEditor.Text = NewsItem.LastEditedBy;
            }

            if (NewsItem.Image != null)
            {
                pnlImage.Visible = true;
                imgNewsItem.ImageUrl = "~/HttpHandlers/ImageHandler.ashx?" + QueryStringConstants.NewsItemImageID + "=" + NewsItem.NewsItemID;
                //why we need to decode here is beyond me
                //maybe the AlternateText property does encode again
                imgNewsItem.AlternateText = Server.HtmlDecode(NewsItem.Title);
            }

        }

        #endregion

        #region ControlEvents

        protected void lbtnDelete_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(DeleteCommandName))
            {
                CommandEventArgs args = new CommandEventArgs(this.DeleteCommandName, this.DeleteCommandArgument);
                OnDeleteCommand(args);
            }
            else
            {
                RepositoryFactory.Instance.GetNewsItemRepository().Delete(NewsItem);

                CacheManager.RemoveLatestComments();
                Cache.Remove(Constants.Cache.Tags);

                //delete button from ViewNewsItem.aspx redirects to Main.aspx because NewsItem has been removed
                Response.Redirect("~/Main.aspx");
            }
        }

        #endregion

        #region DeleteCommand

        private string deleteCommandName;

        [DefaultValue("")]
        public string DeleteCommandName
        {
            get
            {
                return deleteCommandName == null ? String.Empty : deleteCommandName;
            }
            set
            {
                deleteCommandName = value;
            }
        }

        public string deleteCommandArgument;

        [DefaultValue("")]
        public string DeleteCommandArgument
        {
            get
            {
                return deleteCommandArgument == null ? String.Empty : deleteCommandArgument;
            }
            set
            {
                deleteCommandArgument = value;
            }
        }

        protected static readonly object EventCommand = new object();

        public event CommandEventHandler Command
        {
            add
            {
                Events.AddHandler(EventCommand, value);
            }
            remove
            {
                Events.RemoveHandler(EventCommand, value);
            }
        }

        protected virtual void OnDeleteCommand(CommandEventArgs ce)
        {
            CommandEventHandler ceh = this.Events[EventCommand] as CommandEventHandler;
            if (ceh != null)
            {
                ceh(this, ce);
            }

            //This is the trick to cause Command event to bubble up
            base.RaiseBubbleEvent(this, ce);
        }

        #endregion

    }
}